#include "FSFDriver.h"


FSFDriver::FSFDriver(wchar_t* _driverName, wchar_t* _driverExec): Driver(_driverName, _driverExec) 
{
	symLink = new wchar_t[wcslen(_driverName) + 5];
	wcscpy(symLink, L"\\\\.\\");
	wcscat (symLink, _driverName);
}

FSFDriver::~FSFDriver()
{
	delete [] symLink;
	symLink = NULL;
}

BOOL FSFDriver::SendRule(wchar_t* rule)
{
	HANDLE drvHandle = CreateFile(symLink, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
								  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if (drvHandle == INVALID_HANDLE_VALUE)
		return FALSE;

	DWORD bytesReturned;
	if (!DeviceIoControl(drvHandle, IOCTL_SEND_RULE_TO_DRV, rule, (wcslen(rule) + 1) * sizeof(wchar_t), NULL, 0, &bytesReturned, NULL))
		return FALSE;
	
	CloseHandle(drvHandle);
	return TRUE;
}

BOOL FSFDriver::GetRule (wchar_t* rule)
{
	HANDLE drvHandle = CreateFile(symLink, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
							      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if(drvHandle == INVALID_HANDLE_VALUE)
		return FALSE;

	DWORD bytesReturned;
	if (!DeviceIoControl(drvHandle, IOCTL_GET_RULE_LENGTH, NULL, 0, NULL, 0, &bytesReturned, NULL))
		return FALSE;
	
	if (bytesReturned <= 0)
		return FALSE;

	rule = new wchar_t[bytesReturned];
	
	if (!DeviceIoControl(drvHandle, IOCTL_GET_RULE_FROM_DRV, NULL, 0, rule, bytesReturned * sizeof(wchar_t), &bytesReturned, NULL))
		return FALSE;

	CloseHandle(drvHandle);
	return TRUE;
}

BOOL FSFDriver::Hiding(size_t state)
{
	HANDLE drvHandle = CreateFile(symLink, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
								  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if(drvHandle == INVALID_HANDLE_VALUE)
		return FALSE;

	DWORD bytesReturned;
	if (state)
	{
		if(!DeviceIoControl(drvHandle,	IOCTL_HIDING_ON, NULL, 0, NULL, 0, &bytesReturned, NULL))
			return FALSE;
	}
	else 
	{
		if(!DeviceIoControl(drvHandle, IOCTL_HIDING_OFF, NULL, 0, NULL, 0, &bytesReturned, NULL))
			return FALSE;
	}

	CloseHandle(drvHandle);
	return TRUE;
}

BOOL FSFDriver::CheckHiding()
{
	HANDLE drvHandle = CreateFile(symLink, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
								  NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if(drvHandle == INVALID_HANDLE_VALUE)
		return FALSE;

	DWORD bytesReturned;
	if (!DeviceIoControl(drvHandle, IOCTL_GET_RULE_LENGTH, NULL, 0, NULL, 0, &bytesReturned, NULL))
		return FALSE;

	CloseHandle(drvHandle);
	
	if (bytesReturned == 1)
		return TRUE;
	else
		return FALSE;
}